package no.weather.widget;

import java.util.List;

import no.weather.R;
import no.weather.WeatherElement;
import no.weather.WeatherStation;
import no.weather.weatherProvider.StationIsDeletedException;
import no.weather.weatherProvider.WeatherProvider;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.RemoteViews;

public class WidgetProvider extends AppWidgetProvider {
	public static final String GET_NEAREST_STATION = "get nearest station";
	private static final String LOG_ID = "no.weather.widgetProvider";
	public static final String UPDATE_WEATHER_ACTION = "no.weather.widgetProvider.UPDATE_WEATHER_ACTION";
	private AppWidgetManager mAppWidgetManager;

	private Context mContext;

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);
		WidgetDatabase db = new WidgetDatabase(context);
		for (int id : appWidgetIds) {
			db.removeWidget(id);
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		mContext = context;
		mAppWidgetManager = AppWidgetManager.getInstance(context);
		if (intent.getAction().equals(UPDATE_WEATHER_ACTION)) {
			updateAllWidget();
		}
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		mContext = context;
		mAppWidgetManager = appWidgetManager;
		updateWidgets(appWidgetIds);
	}

	public void updateAllWidget() {
		WidgetDatabase db = new WidgetDatabase(mContext);
		updateWidgets(db.getAllWidgetIds());
	}

	private void updateWidgets(int[] appWidgetIds) {
		Log.v(LOG_ID, "Uppdates widgets");
		if (appWidgetIds == null || appWidgetIds.length == 0)
			return;

		WidgetDatabase db = new WidgetDatabase(mContext);
		for (int id : appWidgetIds) {
			WeatherStation station = db.getWeatherStationWithWeatherTypes(id);
			if (station != null) {
				UpdateInfoTask task = new UpdateInfoTask(station, id);
				task.execute(station);
			}
		}
	}

	private class UpdateInfoTask extends
			AsyncTask<WeatherStation, Void, String> {
		private int mAppWidgetId;
		private WeatherStation mStation;

		public UpdateInfoTask(WeatherStation station, int appWidgetId) {
			super();
			mStation = station;
			mAppWidgetId = appWidgetId;
		}

		@Override
		protected String doInBackground(WeatherStation... stations) {
			Log.v(LOG_ID, "Updating widget in async");
			WeatherProvider provider = new WeatherProvider(mContext);
			List<WeatherElement> weather = null;
			if (stations[0].getId().equals(GET_NEAREST_STATION)) {
				WeatherStation nearestStation = provider
						.getNearestStation(stations[0].getTypes());
				try {
					weather = provider.getWeatherNow(nearestStation,null,3600*48);
				} catch (StationIsDeletedException e) {
					mStation.setName(mContext
							.getString(R.string.StationIsDeleted));
					return null;
				}
				mStation.setName(nearestStation.getName());
			} else {
				try {
					weather = provider.getWeatherNow(stations[0],null,3600*48);
				} catch (StationIsDeletedException e) {
					mStation.setName(mContext
							.getString(R.string.StationIsDeleted));
					return null;
				}
			}
			if(weather==null){
				return null;
			}
			for (WeatherElement weatherElement : weather) {
				if (weatherElement.getType().getCode()
						.equals(stations[0].getTypes().get(0).getCode()))
					return weatherElement.getValue();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result == null)
				return;

			RemoteViews views = new RemoteViews(mContext.getPackageName(),
					R.layout.widget_4x1);
			views.setTextViewText(R.id.widgetStation, mStation.getName());
			views.setTextViewText(R.id.widgetValue, result);
			mAppWidgetManager.updateAppWidget(mAppWidgetId, views);
			Log.v(LOG_ID, "The temperature in " + mStation.getName() + " is "
					+ result);
		}
	}
}
